package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.RoleService;

import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult1;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImp implements RoleService {
    @Autowired
    private RoleDao roleDao;

    @Override
    public Set<Permission> findPermissionById(Integer id) {
        return roleDao.findPermissionById(id);
    }

    @Override
    public Set<Role> findAll() {

        return  roleDao.findAll();
    }

    @Override
    public PageResult1 findPage(QueryPageBean queryPageBean) {
        Page page = PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Set<Role>  roleList = roleDao.findConditionByQueryString(queryPageBean.getQueryString());
        return new PageResult1(page.getTotal(),roleList);

    }

    @Override
    public void add(Role role) {
        Integer roleId = role.getId();
        List<Integer> permissionIds = role.getPermissionIds();

        setRoleAndPermission(roleId, permissionIds);
        roleDao.add(role);
    }

    @Override
    public void delete(Integer id) {
        List<Integer> userIds = roleDao.findUserCountIdsByRoleId(id);
        List<Integer> permissionIds = roleDao.findPermissionCountByByRoleId(id);
        if (null != userIds && userIds.size() > 0) {
            roleDao.deleteRelationUSerAndRoleByRoleId(id);
        }
        if (null != permissionIds && permissionIds.size() > 0) {
            roleDao.deleteRelationPermissionAndRoleByRoleId(id);
        }
        roleDao.deleteRoleByRoleId(id);
    }

    public void setRoleAndPermission(Integer roleId,List<Integer> permissionIds ){
        List<Map> list = new ArrayList<>();
        if(permissionIds != null && permissionIds.size() > 0){
            for (Integer permissionId : permissionIds) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("roleId", roleId);
                map.put("permissionId",permissionId);
                list.add(map);
            }
            roleDao.setRolePermission(list);
        }

    }

}
